<?php


/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * @package	
 */
class HelpDeskControllerTickets extends HelpDeskController 
{
	/**
	 * constructor
	 */	
	function __construct() 
	{
		parent::__construct();
		
		// register tasks
		$this->registerTask( 'list', 'display' );
		$this->registerTask( 'new', 'edit' );
		$this->registerTask( 'remove', 'delete' );
		$this->registerTask( 'closeunsatisfactory', 'changestatus' );
		$this->registerTask( 'closepoor', 'changestatus' );
		$this->registerTask( 'closeaverage', 'changestatus' );
		$this->registerTask( 'closegood', 'changestatus' );
		$this->registerTask( 'closegreat', 'changestatus' );		
	}
	
	/**
	 * display 
	 * @return void
	 */
	function display() 
	{
		HelpDeskRequest::setVar( 'view', 'tickets' );
		HelpDeskRequest::setVar( 'layout', 'default'  );
		parent::display();
	}
	
	/**
	 * display the ticket
	 * @return void
	 */
	function view() 
	{
		HelpDeskRequest::setVar( 'view', 'tickets' );
		HelpDeskRequest::setVar( 'layout', 'view'  );
		parent::display();
	}
	
	/**
	 * display the edit form
	 * @return void
	 */
	function edit() 
	{
		HelpDeskRequest::setVar( 'view', 'tickets' );
		HelpDeskRequest::setVar( 'layout', 'form' );
		parent::display();
	}
		
	/**
	 * 
	 * @return unknown_type
	 */
	function save() 
	{
		$model 	= &$this->getModel( 'tickets' );
		$user 	= HelpDeskConfig::getUser();
		
		$msg = new stdClass();
		$msg->type 		= '';
		$msg->message 	= '';
				
		if ( $data = $model->save() ) 
		{
			$msg->type 		= 'message';
			$msg->message  .= HelpDeskText::_( 'Saved' );

			// fire plugins
			$dispatcher = HelpDeskHelperPlugin::getInstance();
			$dispatcher->trigger( 'onAfterSaveSuccess', array( $data, $user, $msg ) );

		} else {
			// save failed
			$msg->type = 'notice';			
			$msg->message = HelpDeskText::_( 'Save Failed' )." - ".$model->getError();
		}

		$link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=list';
		$link = HelpDeskRoute::_( $link );
		$this->setRedirect( $link, $msg->message, $msg->type );
		return;
	}
	
	/**
	 * addcomment
	 * @return void
	 */
	function addcomment() 
	{
		$model = &$this->getModel( 'tickets' );
		$user 	= HelpDeskConfig::getUser();
		
		$msg = new stdClass();
		$msg->type 		= '';
		$msg->message 	= '';
				
		if ( $data = $model->addcomment() ) 
		{
			$msg->type 		= 'message';
			$msg->message  .= HelpDeskText::_( 'New Comment Saved' );

			// fire plugins
			$dispatcher = HelpDeskHelperPlugin::getInstance();
			$dispatcher->trigger( 'onAfterAddCommentSuccess', array( $data, $user, $msg ) );

		} else {
			// save failed
			$msg->type = 'notice';			
			$msg->message = HelpDeskText::_( 'New Comment Failed' )." - ".$model->getError();
		}

		$surrounding = $model->getSurrounding( $data->id );
		$prev = intval( $surrounding["prev"] );
		$next = intval( $surrounding["next"] );
		
		$link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=view&cid[]='.$data->id."&prev={$prev}&next={$next}";
		$link = HelpDeskRoute::_( $link );
		$this->setRedirect( $link, $msg->message, $msg->type );	
	}


	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function changestatus() 
	{
		$model = $this->getModel( 'tickets' );
		$user = HelpDeskConfig::getUser();
		
		$msg = new stdClass();
		$msg->type 		= '';
		$msg->message 	= '';
		$msg->link 		= 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=list';
			
		if ( $data = $model->changestatus() ) 
		{

			$msg->type 		= 'message';
			$msg->message  .= HelpDeskText::_( 'Status Change Success' );

			// fire plugins
			$dispatcher = HelpDeskHelperPlugin::getInstance();
			$dispatcher->trigger( 'onAfterChangeStatusSuccess', array( $data, $user, &$msg ) );
			
			$surrounding = $model->getSurrounding( $data->id );
			$prev = intval( $surrounding["prev"] );
			$next = intval( $surrounding["next"] );
			$msg->link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=view&cid[]='.$data->id."&prev={$prev}&next={$next}";
			
		} else {
			// save failed
			$msg->type = 'notice';			
			$msg->message = HelpDeskText::_( 'Status Change Failed' )." - ".$model->getError();
		}
		
		$msg->link = HelpDeskRoute::_( $msg->link );
		$this->setRedirect( $msg->link, $msg->message, $msg->type );
	}
	
	/**
	 * addfile
	 * @return void
	 */
	function addfile() 
	{
		$model = $this->getModel( 'tickets' );
		$user = HelpDeskConfig::getUser();
		
		$msg = new stdClass();
		$msg->type 		= '';
		$msg->message 	= '';
				
		if ( $data = $model->addfile() ) {

			$msg->type 		= 'message';
			$msg->message  .= HelpDeskText::_( 'New File Saved' );

			// fire plugins
			$dispatcher = HelpDeskHelperPlugin::getInstance();
			$dispatcher->trigger( 'onAfterAddFileSuccess', array( $data, $user, &$msg ) );

		} else {
			// save failed
			$msg->type = 'notice';			
			$msg->message = HelpDeskText::_( 'New File Failed' )." - ".$model->getError();
		}

		$link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=view&cid[]='.$data->id;
		$link = HelpDeskRoute::_( $link );
		$this->setRedirect( $link, $msg->message, $msg->type );	
	}
		
	/**
	 * download the file
	 * @return void
	 */
	function downloadfile() 
	{
		HelpDeskRequest::setVar( 'view', 'tickets' );
		HelpDeskRequest::setVar( 'layout', 'default' );
		$id	= intval ( HelpDeskRequest::getVar( "id" ) );

		$model 	= $this->getModel( 'tickets' );
		$row	= $model->getTable( 'ticket' );
		$row->load( $id );
		$user 	= HelpDeskConfig::getUser();
		$fileid = intval( HelpDeskRequest::getVar( 'fileid' ) );
		
		// cannot view
		if ( !$canView = HelpDeskHelperHelpDesk::canViewAttachment( $fileid, $row->id, $user->id ) ) 
		{
			$link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=list';
			$link = HelpDeskRoute::_( $link, false );
			$msg = HelpDeskText::_( 'Invalid Ticket' );
			$this->setRedirect( $link, $msg, 'notice' );
        	return false;
		}
		
		$file = $model->getTable( 'file' );
		$file->load( (int) $fileid );
	
		if ($viewAttachment = HelpDeskHelperHelpDesk::viewAttachment( $file )) {
			$link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=view&cid[]='.$row->id;
			$link = HelpDeskRoute::_( $link, false );
			$this->setRedirect( $link );
		}
		// parent::display();
	}

	/**
	 * change ticket category
	 * @return void
	 */
	function moveticket() {
		global $mainframe;

		$model = $this->getModel( 'tickets' );
		$user = HelpDeskConfig::getUser();
		
		$msg = new stdClass();
		$msg->type 		= '';
		$msg->message 	= '';
		$msg->link 		= 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=list';
		
		if ( $data = $model->moveticket() ) {

			$msg->type 		= 'message';
			$msg->message  .= HelpDeskText::_( 'Category Change Success' );

			// fire plugins
			$dispatcher = HelpDeskHelperPlugin::getInstance();
			$dispatcher->trigger( 'onAfterMoveTicketSuccess', array( $data, $user, $msg ) );
			
			$surrounding = $model->getSurrounding( $data->id );
			$prev = intval( $surrounding["prev"] );
			$next = intval( $surrounding["next"] );
			
			$msg->link = 'index.php?option='._THISCOMPONENT.'&controller=tickets&task=view&cid[]='.$data->id."&prev={$prev}&next={$next}";

		} else {
			// save failed
			$msg->type = 'notice';			
			$msg->message = HelpDeskText::_( 'Category Change Failed' )." - ".$model->getError();
			
		}

		$msg->link = HelpDeskRoute::_( $msg->link );
		$this->setRedirect( $msg->link, $msg->message, $msg->type );	
	}
	
	/**
	 * 
	 * @return 
	 */
	function verifyFields()
	{
		$success = true;

		// get elements from post
			// $elements = json_decode( HelpDeskRequest::getVar( 'elements', '', 'post', 'string' ) );
			$elements = json_decode( preg_replace('/[\n\r]+/', '\n', HelpDeskRequest::getVar( 'elements', '', 'post', 'string' ) ) );
			// elements is an array of objects
			// $object->name
			// $object->value
			// $object->id (if present, is the element id in the form)
		
		// loop through every field in the form
			for ($i=0; $i<count($elements); $i++) {
				$element = $elements[$i];
				if (trim(strtolower($element->name)) == 'categoryid') {
					$categoryid = $element->value;
					$catname = 'cat'.$categoryid;
				}
				if (trim(strtolower($element->name)) == 'subject') {
					$subject = $element->value;
				}
				if (trim(strtolower($element->name)) == 'description') {
					$description = $element->value;
				}
				if (trim(strtolower($element->name)) == 'newuser_email') {
					$newuser_email = $element->value;
				}
			}
			
		// use 'categoryid' to select fields to examine
			$n=0;
			$search = array( '[', ']' );
			$checks = array();
			for ($i=0; $i<count($elements); $i++) {
				$element = $elements[$i];
				$exploded = explode( '_', $element->name, '2' );
				if ($exploded[0] == $catname) {
					$checks[$n] = new stdClass();
					$checks[$n]->name = str_replace( $search, '', $exploded[1]);
					$checks[$n]->value = trim( $element->value );
					$n++;
				}
			}

		// $checks should now contain an array of objects
		// that need to be verified	(if any)		
			// $html .= HelpDeskConfig::dump( $checks );

		$msg = new stdClass();
		$msg->message = '';
		$msg->error = '';
		
		// first check subject and description
			if (empty($subject)) {
				$msg->message .= '<li>"'.HelpDeskText::_( 'Subject' ).'" '.HelpDeskText::_( 'is Required' ).'</li>';
				$msg->error = '1';				
			}
			if (empty($description)) {
				$msg->message .= '<li>"'.HelpDeskText::_( 'Description' ).'" '.HelpDeskText::_( 'is Required' ).'</li>';
				$msg->error = '1';				
			}

		// then check if email field is needed
			$config = HelpDeskConfig::getInstance();
			$require_login = $config->get( 'require_login', '1' );
			$user 	= HelpDeskConfig::getUser();
			if (!$require_login && !$user->id && empty($newuser_email)) {
				$msg->message .= '<li>"'.HelpDeskText::_( 'Email Address' ).'" '.HelpDeskText::_( 'is Required' ).'</li>';
				$msg->error = '1';				
			}
						
		// find and load the __fields table row for each object in the $check array
		// based on its field name		
		// check its required status
		// if required and value = '' return an error message for that field
			for ($i=0; $i<count($checks); $i++) {
				$check = $checks[$i];
				$field = HelpDeskHelperField::getFromFieldname( $check->name );
				$isRequired = HelpDeskHelperField::isRequired( $field->id, $categoryid );
				if ($isRequired && empty( $check->value) ) {
					$msg->message .= '<li>"'.HelpDeskText::_( $field->title ).'" '.HelpDeskText::_( 'is Required' ).'</li>';
					$msg->error = '1';
				}
			}

		// set response array
			// <li>Warning - Invalid Entries</li>
			$response = array();
			$txt = "";
			if (!empty($msg->error))
			{
				$txt = '
				<dl id="system-message">
				<dt class="notice"></dt>
				<dd class="notice message fade">
					<ul>'.
					$msg->message						
					.'</ul>
				</dd>
				</dl>
				';
			}
	        $response['msg'] = $txt;
		    $response['error'] = $msg->error;
			
		// encode and echo (need to echo to send back to browser)
		echo ( json_encode( $response ) );

		return $success;	
	}
	
}